package com.spark.trouble.handle

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.spark.colliery.common.ext.gone
import com.spark.common.Api
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.*
import com.spark.common.helper.Picker
import com.spark.common.model.ImgUploadResultModel
import com.spark.common.model.db.HTSubmitDetailModel
import com.spark.trouble.R
import kotlinx.android.synthetic.main.item_hidden_trouble_source.*
import org.jetbrains.anko.find

/**
 * 危险源
 */
class DangerSourceFragment : BaseFragment() {
    private var index: Int = 0
    private lateinit var dangerSourceImageAdapter: DangerSourceImageAdapter
    // 包含➕的本地图片地址
    private val localCover = mutableListOf<String>()
    // 上传的url地址
    private val cloudCover = mutableListOf<String>()
    // ➕ absolute path
    private lateinit var plusImgPath: String
    private val cloudFileId = mutableListOf<String>()
    // 危险源详情
    private var dangerous: HTSubmitDetailModel? = null

    private var onFragmentDeleteListener: OnFragmentDeleteListener? = null
    private var canEdit = false

    companion object {
        fun newInstance(index: Int = 0, dangerous: HTSubmitDetailModel? = null, canEdit: Boolean): DangerSourceFragment {
            val target = DangerSourceFragment()
            val args = Bundle()
            args.putInt(Const.tag_index, index)
            args.putSerializable("dangerous", dangerous)
            args.putBoolean("canEdit", canEdit)
            target.arguments = args
            return target
        }
    }

    fun addDeleteListener(listener: OnFragmentDeleteListener) {
        onFragmentDeleteListener = listener
    }

    override fun contentResId(): Int {
        return R.layout.item_hidden_trouble_source
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // arguments
        arguments?.apply {
            index = getInt(Const.tag_index) ?: 0
            dangerous = getSerializable("dangerous")?.let { it as HTSubmitDetailModel }
            canEdit = getBoolean("canEdit", false)
        }
        // img_plus_add
        plusImgPath = context.relAbsPath(R.drawable.img_plus_add)
        if (!localCover.contains(plusImgPath))
            localCover.add(plusImgPath)

        dangerSourceImageAdapter = DangerSourceImageAdapter(R.layout.item_danger_source_img, canEdit).apply {
            // restore images
            dangerous?.apply {
                imgs.forEach {
                    addData(it)
                }
            }
            // 默认➕图片
            if (canEdit && !data.contains(plusImgPath))
                addData(plusImgPath)

            setOnItemClickListener { adapter, _, position ->
                val dataSize = adapter.data.size
                val item = adapter.data[position]
                if (item == plusImgPath) {
                    imgClick(position, dataSize)
                } else {
                    success("点击图片【$position】")
                }
            }
            setOnItemChildClickListener { _, _, position ->
                val imgPath = dangerSourceImageAdapter.data[position]
                if (localCover.contains(imgPath))
                    localCover.remove(imgPath)
                if (position in 0 until cloudCover.size - 1) {
                    cloudCover.removeAt(position)
                    cloudFileId.removeAt(position)
                }
                if (localCover.size < 9 && !localCover.contains(plusImgPath))
                    localCover.add(plusImgPath)
                dangerSourceImageAdapter.replaceData(localCover)
            }
            registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
                override fun onChanged() {
                    super.onChanged()
                    val dataIsEmpty = dangerSourceImageAdapter.data.isEmpty()
                    recy_source_imgs.gone(dataIsEmpty)
                    divider2.gone(dataIsEmpty)
                }
            })
        }
        recy_source_imgs.apply {
            adapter = dangerSourceImageAdapter
            val glm = object : GridLayoutManager(context, 4, GridLayoutManager.VERTICAL, false) {
                override fun canScrollVertically(): Boolean {
                    return false
                }

                override fun canScrollHorizontally(): Boolean {
                    return false
                }

                override fun isAutoMeasureEnabled(): Boolean {
                    return true
                }
            }
            layoutManager = glm
        }
        iv_delete.setOnClickListener {
            onFragmentDeleteListener?.onDelete(index)
        }
        iv_delete.gone(!canEdit)
        et_act_desc.inputType = if (canEdit) EditText.AUTOFILL_TYPE_TEXT else EditText.AUTOFILL_TYPE_NONE
        // retore
        restore()

        savedInstanceState?.apply {
            localCover.clear()
            localCover.addAll(getStringArray("localCover").toMutableList())
            cloudFileId.clear()
            cloudFileId.addAll(getStringArray("cloudFileId").toMutableList())
            cloudCover.clear()
            cloudCover.addAll(getStringArray("cloudCover").toMutableList())
            dangerSourceImageAdapter.replaceData(localCover)
        }
        et_act_desc.requestFocus()
        //tv_handle_man.text = Const.getUser()?.user?.name
        tv_handle_man.gone(true)
        tv_handle_time.text = sdf().format(System.currentTimeMillis())
    }


    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.apply {
            putStringArray("localCover", localCover.toTypedArray())
            putStringArray("cloudCover", cloudCover.toTypedArray())
            putStringArray("cloudFileId", cloudFileId.toTypedArray())
            putInt("position", index)
        }
    }

    /**
     * restore the state
     */
    private fun restore() {
        dangerous?.apply {
            tv_desc.text = this.troubleContent
            et_act_desc.setText(this.sourceDesc)
            tv_handle_man.text = handleMan
            try {
                tv_handle_time.text = sdf().format(handleTime.toLong())
            } catch (e: Exception) {
                e.printStackTrace()
                LogUtils.d("数据格式化错误")
            }
        }
    }

    @SuppressLint("CheckResult")
    private fun imgClick(position: Int, dataSize: Int) {
        if (position == dataSize - 1) {
            activity?.apply {
                Picker(this).show {
                    // LogUtils.e("【路径】$it")
                    uploadImg(it)
                }
            }
        } else {
            success("点击图片【$position】")
        }
    }

    @SuppressLint("CheckResult")
    private fun uploadImg(imgPath: String) {
        Api.upload(imgPath)
                .subscribe(
                        {
                            Gson().fromJson(it, ImgUploadResultModel::class.java)?.apply {
                                if (code == "200") {
                                    if (resultMaps.isNotEmpty()) {
                                        resultMaps[0].apply {
                                            if (!cloudCover.contains(this.url)) {
                                                cloudCover.add(this.url)
                                                cloudFileId.add(this.fileId.toString())
                                            }
                                            if (!localCover.contains(imgPath))
                                                localCover.add(0, imgPath)
                                            if (localCover.size >= 9)
                                                localCover.removeAt(8)
                                            dangerSourceImageAdapter.replaceData(localCover)
                                        }
                                    }
                                }
                            }
                        },
                        {
                            hideLoader()
                            it.printStackTrace()
                            report(it)
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("上传中...")
                        }
                )
    }

    /**
     * summary the data that the page could offer
     */
    fun summary(): HTSubmitDetailModel {
        val desc = view?.find<EditText>(R.id.et_act_desc)?.text.toString().trim()
        return HTSubmitDetailModel(
                sourceDesc = dangerous?.sourceDesc ?: "",
                troubleContent = desc,
                fields = cloudFileId.append(","),
                sourceprocessorId = dangerous?.sourceprocessorId ?: "",
                sourceId = dangerous?.sourceId ?: "",
                sourceFolder = dangerous?.sourceFolder ?: "",
                sourceMoney = dangerous?.sourceMoney ?: "",
                sourceScore = dangerous?.sourceScore ?: ""
        )
    }
}


interface OnFragmentDeleteListener {
    fun onDelete(position: Int)
}

class DangerSourceImageAdapter(layoutRes: Int, var canEdit: Boolean) : BaseQuickAdapter<String, BaseViewHolder>(layoutRes) {
    override fun convert(helper: BaseViewHolder?, item: String?) {
        if (item == null) return
        helper?.apply {
            val ivDangerImg = getView<ImageView>(R.id.iv_danger_img)
            if (item == mContext.relAbsPath(R.drawable.img_plus_add)) {
                ivDangerImg.setImageResource(R.drawable.img_plus_add)
            } else {
                ivDangerImg.local(item)
            }

            getView<ImageView>(R.id.iv_delete).apply {
                if (canEdit) {
                    gone(mContext.relAbsPath(R.drawable.img_plus_add) == item)
                } else
                    gone(true)
                setOnClickListener {
                    onItemChildClickListener?.onItemChildClick(this@DangerSourceImageAdapter, it, adapterPosition)
                }
            }
        }
    }
}